awPlus.drawBattles = function(bid, data) {
  $('#'+bid).html('<table id="'+bid+'_tbl" border="0" width="100%" cellpadding="1" style="padding: 10px; font-size: 11px;" cellspacing="1">'
    +'<tbody><tr bgcolor="#202060">'
    +'<th>ID</th><th>Attacker</th><th>Defender</th><th>Date</th>'
    +'</tr></tbody></table>');
  
  var table = $('#'+bid+'_tbl tbody');

  var attacker, defender, color_att, color_def, ndt,sdt;
  for (i in data.battles) {
    with (data.battles[i]) {
      if (att_name == null) att_name = 'unknown';
      if (def_name == null) def_name = 'unknown';
      attacker = (att_tag ? '['+att_tag+'] ':'') + att_name;
      defender = (def_tag ? '['+def_tag+'] ':'') + def_name;

      color_att = (player_id_win == player_id_att) ? 'green' : 'red';
      color_def = (player_id_win == player_id_def) ? 'green' : 'red';
      
      ndt = new Date((dt*1000)+((new Date().getTimezoneOffset()+120)*60*1000));
      sdt = ndt.getFullYear()+'-'+(ndt.getMonth()+1)+'-'+ndt.getDate()+' '
            +ndt.getHours()+':'+ndt.getMinutes()+':'+ndt.getSeconds();

      table.append('<tr align="center" bgcolor="#404040" valign="top">'
        +'<td>'+system_id+' '+planet+'</td>'
        +'<td style="color: '+color_att+';" title="'+cv_att+'">'+cv_att+'<br />'+attacker+'</td>'
        +'<td style="color: '+color_def+';" title="'+cv_def+'">'+cv_def+'<br />'+defender+'</td>'
        +'<td>'+sdt+'</td>'
        +'</tr>');
    }
  }
}

awPlus.showSystemDialog = function (sid, pos, options) {
  function btn_system_BBCode () {
    var id = $(this).attr('id');
    var bid = id + '_bb';
    var obid = $('#'+bid);
    if (obid.length == 0) {
      var x = $(this).clone();
      x.attr('id', bid);
      $(this).after(x).hide();
      
      $('#'+bid).html('<textarea id="'+bid+'_code" style="margin: 10px; width: 90%; height: 200px;"></textarea>');
      
      var sys = $(this).siblings('.ui-dialog-titlebar').children('.ui-dialog-title').text().match(/(.*?) \((-?\d+\/-?\d+)\) \[(\d+)\]$/);
      
      $('#'+bid+'_code').text('Export of System [b]'+sys[3]+' - '+sys[1]+' ('+sys[2]+')[/b]\r\n[size=13]\r\n[i]pid pop sb   owner[/i][/size][size=14]\r\n');
      
      $('table tr:gt(0)', this).each(function(i) {
        var color;
        switch ($(this).attr('bgcolor')) {
          case '#602020': color = 'red'; break;
          case '#305050': color = 'green'; break;
          case '#404040': color = 'darkgrey'; break;
        }
        var pid = $('td:eq(0)', this).text();
        pid = pid.length == 2 ? pid : '0'+pid;
        var pop = $('td:eq(1)', this).text();
        pop = pop.length == 2 ? pop : '0'+pop;
        var sb = $('td:eq(2)', this).text();
        sb = sb.length == 2 ? sb : '0'+sb;
        var user = $('td:eq(3)', this).text();
        var line = '[color='+color+']'+pid+'  '+pop+'  '+sb+'   '+user+'[/color]\r\n';
        
        $('#'+bid+'_code').append(line);
      });
      $('#'+bid+'_code').append('[/size]\r\nGenerated by [url=http://code.google.com/p/awplus/]awPlus[/url] at '+ new Date().toString());
      $('#'+bid+'_code').focus().get(0).select();
      
    }
    else {
      obid.remove();
      $(this).show();
    }
  }

  function btn_system_Battles () {
    var id = $(this).attr('id');

    var bid = id + '_bt';
    var obid = $('#'+bid);
    if (obid.length == 0) {
      var x = $(this).clone();
      x.attr('id', bid);
      $(this).after(x).hide();

      var sys = $(this).siblings('.ui-dialog-titlebar').children('.ui-dialog-title').text().match(/(.*?) \((-?\d+\/-?\d+)\) \[(\d+)\]$/);

      awPlus.loadAwPlusData('system_battles/'+sys[3], function(data) {
        awPlus.drawBattles(bid, data);
      });
    }
    else if (obid.is(':hidden')) {
      $(this).hide();
      obid.show();
    }
    else {
      obid.hide();
      $(this).show();
    }
  }


  if ($('#apsys_'+ sid).dialog('open').size()) { return; }

  pos = pos || $('#'+ sid).offset();
  options = options || {};

  $('body').append('<div id="apsys_'+sid+'" class="apsys"></div>');
  
  var settings = {
    resizable: false,
    position: (typeof pos == 'object') ? [pos.left-150, pos.top-175] : 'center',
    buttons: {
      'Reload': function() {
        $(this).text('');
        $(this).getSystemData(sid);
      },
      'BBCode': btn_system_BBCode,
      'Battles': btn_system_Battles,
      'Close': function() { $(this).dialog('close'); }
    }
  }
  jQuery.extend(settings, options);
  $('#apsys_'+ sid).dialog(settings);

  $('#apsys_'+ sid).getSystemData(sid);
}

jQuery.fn.getSystemData = function (sid, title_on_body) {
  title_on_body = title_on_body || false;
  
  function initPlayer (e) {
    var pid = this.href.match(/([0-9]+)$/)[1];
    $(this).addClass('applayer').addClass('applayer_'+pid).data('ap_pid', pid);
    this.href = "javascript:void(0);";

    $(this).click(function() {
      var pos = $(this).offset();
      awPlus.showPlayerDialog(pid, pos);
    });
  }

  return this.each(function() {
    var object = $(this);
    object.html('Loading...');

    $.get('/0/Map/Detail.php/?nr='+sid,
      function(data) {
        var syshtml = data.replace(/\n/g, '');
        // If system is over than bio
        if (syshtml.length < 3000) {
          awPlus.loadAwPlusData('system_all/'+sid, function(data) {
            var aphtml = '<table id="apsys_tbl_'+data.id+'" cellspacing="1" cellpadding="1" border="0" width="100%" style="padding: 10px; font-size: 11px"><tr bgcolor="#808060" align="center"><td nowrap="nowrap">ID</td><td nowrap="nowrap"><a href="/0/Glossary//?id=22">Pop</a></td><td nowrap="nowrap"><a href="/0/Glossary//?id=16">Sb</a></td><td nowrap="nowrap">Owner</td></tr>';
            
            var ptag, color, d;
            for (i in data.planets) {
              d = data.planets[i];
              ptag = d.tag ? '['+d.tag+'] ' : '';
              color = d.siege ? '#602020' : '#888888';
              aphtml += '<tr bgcolor="'+color+'" align="center">'
                        + '<td nowrap="nowrap">'+i+'</td>'
                        + '<td nowrap="nowrap">'+d.population+'</td>'
                        + '<td nowrap="nowrap">'+d.starbase+'</td>'
                        + '<td nowrap="nowrap"><a href="xxxx='+d.player_id+'">'+ptag+d.name+'</a></td>'
                      +'</tr>';
            }
            
            aphtml += '</table>';
            object.html(aphtml);
            
            $('a', '#apsys_tbl_'+data.id).each(initPlayer);
            
            var systitle = data.name+' ('+data.x+'/'+data.y+') ['+data.id+']';
            if (title_on_body) {
              object.prepend('<br /><div align="center">'+systitle +'</div>');
            }
            else {
              object.siblings('.ui-dialog-titlebar').children('.ui-dialog-title').html(systitle);
            }
          });
          
          return;
        }
        var systitle = $('table:eq(2) tr:eq(0) td', syshtml).html().replace('Planets at ', '') + ' ['+sid+']';
        var aphtml = $('table:eq(2)', syshtml).find('tr:eq(0)').remove().end().html();
        aphtml = '<table id="apsys_tbl_'+sid+'" cellspacing="1" cellpadding="1" border="0" width="100%" style="padding: 10px; font-size: 11px">'+aphtml+'</table>';

        if (title_on_body) {
          aphtml = '<br /><div align="center">'+systitle +'</div>'+ aphtml;
        }
        else {
          object.siblings('.ui-dialog-titlebar').children('.ui-dialog-title').html(systitle);
        }

        var player_id_list = [];

        object.html(aphtml)
          .find('table tr:gt(0) td a')
            .each(initPlayer)
            .each(function() {
              var pid = $(this).data('ap_pid');
              if (player_id_list.indexOf(pid) > -1) return;

              player_id_list.push(pid);
            })
          .end();
       
        awPlus.loadAwPlusData('player_info_list/'+player_id_list.join(','), function(data) {
          for (jpid in data) {
            if (data[jpid]['tag'] == null) continue;
            $('#apsys_tbl_'+sid+' .applayer_'+jpid).prepend('['+data[jpid]['tag']+'] ');
          }
        });
        
        // Change table headers
        $('tr:eq(0)', '#apsys_tbl_'+sid)
          .find('td:eq(1) a').text('Pop').end()
          .find('td:eq(2) a').text('Sb').end();

        awPlus.loadAwPlusData('system_all/'+sid, function (data) {
          $('tr:gt(0)', '#apsys_tbl_'+sid).each(function(i) {
            i++;
            var planet = data['planets'][i+''];
            if (planet == null) return;
            
            // Add icons
            var actual_pid = parseInt($('td:eq(3) a', this).data('ap_pid'));
            // Free Planet
            if (isNaN(actual_pid)) return;

            // Colonized
            if (actual_pid != planet.player_id) {
              if (planet.name == null) planet.name = "Free Planet";
              var tag = planet.tag ? '['+planet.tag+'] ' : '';
              $('td:eq(3)', this).prepend('<span class="ui-icon ui-icon-home" style="float: right;" title="Last Player: '+tag + planet.name+'"  />');
            }

            // Sieged
            if ($(this).is('[bgcolor=#602020]') != planet.siege) {
              $('td:eq(3)', this).prepend('<span class="ui-icon ui-icon-alert" style="float: right;" title="Fight Alert!" />');
            }

            // Now, if free planet or unknown, return!
            if (planet.player_id <= 2) return;
            
            // Paint pop evolution
            var pop = $('td:eq(1)', this).text();
            if (pop != planet.population) {
              pop = parseInt(pop) - parseInt(planet.population);
              $('td:eq(1)', this)
                .attr('title', pop > 0 ? '+'+pop : pop)
                .wrap('<span style="color: '+(pop>0?'green':'red')+';"></span>');
            }

            // Paint Sb evolution
            var sb = $('td:eq(2)', this).text();
            if (sb != planet.starbase) {
              sb = parseInt(sb) - parseInt(planet.population);
              $('td:eq(1)', this)
                .attr('title', sb > 0 ? '+'+sb : sb)
                .wrap('<span style="color: '+(sb>0?'green':'red')+';"></span>');
            }

          });
        });
       
        if (!title_on_body) {
          $('td', object).attr('nowrap', 'nowrap');
          object.dialog('open');
        }
      });
  });
}
  
  

awPlus.showPlayerDialog = function (pid, pos) {
  var appla;
  function getPlayerData (pid) {
    appla.html('Loading...');

    $.get('/0/Player/Profile.php/?id='+pid,
      function(data) {
        var plahtml = data.replace(/\n/g, '');
        var aphtml = '<table width="100%" style="padding: 10px;">';
        aphtml += $('table:eq(2)', plahtml).html();
        aphtml += '</table>';

        var aptitle = $('table tr td center', aphtml).html().replace('Premium Member', '');

        appla.siblings('.ui-dialog-titlebar').addClass('ui-state-active');
        
        appla
          .siblings('.ui-dialog-titlebar')
          .children('.ui-dialog-title')
            .html(aptitle)
          .end();
        appla
          .html(aphtml)
          .find('table:eq(1) tr:eq(0) td center')
            .append('&nbsp;['+pid+']')
          .end();

        $('td', appla).attr('nowrap', 'nowrap');
        
        appla
          .dialog('option', 'width', $('table:first', appla).width() + 50)
          //.dialog('close').dialog('open');
          .dialog('open');
      });   
  }

  function btn_player_Battles () {
    var id = $(this).data('ap_pid');
    var bid = 'p_'+id+'_bt';
    var obid = $('#'+bid);
    if (obid.length == 0) {
      var x = $(this).clone();
      x.attr('id', bid);
      $(this).after(x).hide();

      awPlus.loadAwPlusData('player_battles/'+id, function(data) {
        awPlus.drawBattles(bid, data);
      });
    }
    else if (obid.is(':hidden')) {
      $(this).hide();
      obid.show();
    }
    else {
      obid.hide();
      $(this).show();
    }
  }

  if ($('#appla_'+ pid).dialog('open').size()) { return; }

  $('body').append('<div id="appla_'+pid+'" class="appla"></div>');
  
  appla = $('#appla_'+ pid);
  appla.data('ap_pid', pid);
  appla.dialog({
      resizable: false,
      position: (typeof pos == 'object') ? [pos.left-135, pos.top-205] : 'center',
      dialogClass: 'appladet',
      buttons: {
        'Reload': function() {
          $(this).empty();
          getPlayerData(pid);
        },
        'Battles': btn_player_Battles,
        'Close': function() { $(this).dialog('close'); }
      }
    });

  getPlayerData(pid);
}


awPlus.jq_zindex = 100;
jQuery.fn.toFront = function() {
  return this.each(function() {
    $(this).css('z-index', ++awPlus.jq_zindex);
  });
}

awPlus.ap_player_attachClickByClass = function (selector) {
  selector = selector || '.ap_player';
  $(selector).click(function(i) {
    var pid = this.id.match(/_(\d+)$/)[1];
    awPlus.showPlayerDialog(pid);
  });
}

jQuery(function($) {

  // apply all player links
  var pid_list = [];
  $('a[href*=Player/Profile.php]').each(function(i) {
    var xpid = $(this).attr('href').match(/id=([0-9]+)$/)[1];
    this.id = 'ap_player_'+i+'_'+xpid;
    this.href = 'javascript: void(0);';
    if (pid_list.indexOf(xpid) == -1) pid_list.push(xpid);
    $(this)
      .addClass('ap_player')
      .data('player_id', xpid)
      .click(function() {
        awPlus.showPlayerDialog(xpid);
      });
  });

  if (pid_list.length > 0) {
    awPlus.loadAwPlusData('player_info_list/'+pid_list.join(','), function(data){
      $('.ap_player').each(function() {
        var pid = this.id.match(/player_\d+_(\d+)/)[1];
        if (data[pid] == null || data[pid].tag == null) return;
        $(this).prepend('['+data[pid].tag+'] ');
      });
    });
  }

  $('tr[onclick]').each(function () {
    var x = $(this).attr('onclick');
    if (x.toString().match(/Player\/Profile/)) {
      $(this).attr('onclick', '');
    }
  });

});
